package cqrtplm.common.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import com.hustcad.plm.basic.log.LogEventEnum;
import com.hustcad.plm.basic.log.TyplmLogger;
import com.hustcad.plm.basic.vo.cad.CadDownloadFileVO;
import com.hustcad.plm.caddoc.mapper.TyplmCADDocMasterMapper;
import com.hustcad.plm.pdm.ec.module.dto.ECObjData;
import com.hustcad.plm.pdm.ec.module.vo.ECLinkObjDataCommonVO;
import com.hustcad.plm.pdm.ec.service.TyplmEcAgainstDataService;
import com.hustcad.plm.pdm.file.model.dto.DownloadFileDTO;
import com.hustcad.plm.pdm.file.model.vo.DownLoadFile.DownLoadFileVO;
import com.hustcad.plm.pdm.file.service.upload.TyplmFileTransferService;
import com.hustcad.plm.pdm.file.util.TyplmDownloadToolUtil;
import com.hustcad.plm.pdm.filevault.service.TyplmContentDataService;
import com.hustcad.plm.pdm.filevault.service.TyplmContentReferenceLinkService;
import com.hustcad.plm.pdm.filevault.service.TyplmEncryptService;
import com.hustcad.plm.pdm.flowbusiness.model.entity.FlowChangeRequestView;
import com.hustcad.plm.pdm.flowbusiness.model.entity.FlowChgFormView;
import com.hustcad.plm.pdm.flowbusiness.model.entity.FlowObject;
import com.hustcad.plm.pdm.flowbusiness.model.entity.WorkFlowObjectPackage;
import com.hustcad.plm.pdm.form.model.vo.PdmFormColumn;
import com.hustcad.plm.pdm.form.service.TyplmDynamicFormService;
import com.hustcad.plm.pdm.partbom.dto.ChildPartsFiltersDTO;
import com.hustcad.plm.pdm.partbom.dto.ExpandBomTreeByFilterDTO;
import com.hustcad.plm.pdm.partbom.query.PartUsageCountQuery;
import com.hustcad.plm.pdm.partbom.service.TyplmPartBomService;
import com.hustcad.plm.pdm.partbom.service.TyplmPartUsageService;
import com.hustcad.plm.pdm.partbom.vo.PartBomTreeByFilterVO;
import com.hustcad.plm.pdm.partbom.vo.PdmPartFormData;
import com.hustcad.plm.pdm.partbom.vo.usagecount.PartUsageCountVO;
import com.hustcad.plm.pdm.type.model.vo.TypeTree;
import com.hustcad.plm.pdm.type.service.TyplmTypeService;
import com.hustcad.plm.pdm.user.service.TyplmUserService;
import com.hustcad.plm.pdm.workflow.model.entity.WorkFlowContainerView;
import com.hustcad.plm.pdm.workflow.service.TyplmWorkFlowContainerService;
import com.lark.oapi.okhttp.MediaType;
import com.lark.oapi.okhttp.OkHttpClient;
import com.lark.oapi.okhttp.Request;
import com.lark.oapi.okhttp.RequestBody;
import com.lark.oapi.okhttp.Response;
import com.ty.basic.constant.TableTypeConstrant;
import com.ty.basic.entity.IdentifierEntity;
import com.ty.basic.entity.cad.CADDocMasterDO;
import com.ty.basic.entity.org.UserDO;
import com.ty.basic.entity.part.PartDO;
import com.ty.basic.session.TyAccountContext;
import com.ty.basic.utils.PathUtil;
import cqrtplm.common.CommonService;
import cqrtplm.constant.RTErrorCodeEnum;
import cqrtplm.dto.RTExportFileDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.io.*;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CommonServiceImpl implements CommonService {
    @Resource
    private TyplmCADDocMasterMapper typlmCADDocMasterMapper;
    @Resource
    private TyplmWorkFlowContainerService typlmWorkFlowContainerService;
    @Resource
    private TyplmEcAgainstDataService typlmEcAgainstDataService;
    @Resource
    private TyplmPartBomService typlmPartBomService;
    @Value("${file.default.dir}")
    private String fileExportDefaultDir;
    @Value("${ftp.server}")
    private String server;
    @Value("${ftp.port}")
    private int port;
    @Value("${ftp.username}")
    private String username;
    @Value("${ftp.password}")
    private String password;
    @Resource
    private TyplmContentReferenceLinkService typlmContentReferenceLinkService;
    @Resource
    private TyplmFileTransferService typlmFileTransferService;
    @Resource
    private TyplmEncryptService typlmEncryptService;
    @Resource
    private TyplmContentDataService typlmContentDataService;
    @Resource
    private TyplmLogger typlmLogger;
    @Resource
    private TyplmUserService typlmUserService;
    @Resource
    private TyplmPartUsageService typlmPartUsageService;
    @Resource
    private TyplmDynamicFormService typlmDynamicFormService;
    @Resource
    private TyplmTypeService typlmTypeService;

    @Override
    public boolean cadDocIsExistByNumber(String number) {
        Example example = new Example(CADDocMasterDO.class);
        example.createCriteria().andEqualTo("docnumber", number);
        List<CADDocMasterDO> cadDocMasterDOList = typlmCADDocMasterMapper.selectByExample(example);
        return CollUtil.isNotEmpty(cadDocMasterDOList);
    }

    @Override
    public List<IdentifierEntity> getFlowObjListByWorkFlowContainer(WorkFlowContainerView workFlowContainerView) {
        List<IdentifierEntity> flowList = new ArrayList<>();
        if ((workFlowContainerView instanceof WorkFlowObjectPackage)) {
            log.info("当前流程属于普通流程");
            WorkFlowObjectPackage workFlowObjectPackage = (WorkFlowObjectPackage) workFlowContainerView;
            List<FlowObject> flowObjectList = workFlowObjectPackage.getFlowObjectList();
            if (CollUtil.isNotEmpty(flowObjectList)) {
                flowList = flowObjectList.stream().map(
                        m -> new IdentifierEntity(m.getRefObjectOid(), m.getRefObjectOtype())).distinct().collect(
                        Collectors.toList());
            }
        } else if (workFlowContainerView instanceof FlowChgFormView) {
            log.info("当前流程属于变更流程/发布流程");
            FlowChgFormView flowChgFormView = (FlowChgFormView) workFlowContainerView;
            List<ECObjData> flowObjectList = flowChgFormView.getChgFormVO().getEcAffectVOS();
            if (CollUtil.isNotEmpty(flowObjectList)) {
                flowList = flowObjectList.stream().map(m -> new IdentifierEntity(m.getOid(), m.getOtype())).distinct()
                        .collect(Collectors.toList());
            }
        } else if (workFlowContainerView instanceof FlowChangeRequestView) {
            log.info("当前流程属于变更请求流程");
            List<ECLinkObjDataCommonVO> ecLinkObjDataCommonVOS = typlmEcAgainstDataService.batchGetAffectedObjectListByOids(
                    Collections.singletonList(workFlowContainerView.getBaseObjectOid()),
                    workFlowContainerView.getBaseObjectOtype());
            if (CollUtil.isNotEmpty(ecLinkObjDataCommonVOS)) {
                flowList = ecLinkObjDataCommonVOS.stream().map(m -> new IdentifierEntity(m.getOid(), m.getOtype()))
                        .distinct().collect(Collectors.toList());
            }
        }
        log.info("流程中对象：{}", flowList);
        return flowList;
    }


    @Override
    public List<IdentifierEntity> getFlowObjListByWorkFlowContainer(BigInteger workFlowContainerId) {
        WorkFlowContainerView workFlowContainerView = typlmWorkFlowContainerService.getWorkFlowContainerDetailByPrimaryKey(
                workFlowContainerId);
        if (Objects.isNull(workFlowContainerView)) {
            log.info("未找到 {} 对应的流程容器", workFlowContainerId);
            return new ArrayList<>();
        }
        return getFlowObjListByWorkFlowContainer(workFlowContainerView);
    }


    @Override
    public PartBomTreeByFilterVO queryChildParts(String partNumber, String partOid, String view, boolean isNestedTree,
                                                 String lifecycleStateKey, String expandLevel) {
        return queryChildParts(partNumber, partOid, view, isNestedTree, lifecycleStateKey, expandLevel, Boolean.FALSE);
    }

    @Override
    public PartBomTreeByFilterVO queryChildParts(String partNumber, String partOid, String view, boolean isNestedTree,
                                                 String lifecycleStateKey, String expandLevel, boolean isParent) {
        List<ChildPartsFiltersDTO> conditions = new ArrayList<>();
        ChildPartsFiltersDTO childPartsFiltersDTO = new ChildPartsFiltersDTO();
        childPartsFiltersDTO.setExpandCondition("latest");
        if (StringUtils.isNotBlank(lifecycleStateKey)) {
            childPartsFiltersDTO.setLifecycleStateKey(lifecycleStateKey);
        }
        childPartsFiltersDTO.setView(view);
        conditions.add(childPartsFiltersDTO);
        ExpandBomTreeByFilterDTO expandBomTreeByFilterDTO = new ExpandBomTreeByFilterDTO();
        expandBomTreeByFilterDTO.setConditions(conditions);
        expandBomTreeByFilterDTO.setFatherOid(partOid);//设置oid
        expandBomTreeByFilterDTO.setFatherNumber(partNumber);
        expandBomTreeByFilterDTO.setFatherOtype(TableTypeConstrant.TY_PART_OTYPE);
        expandBomTreeByFilterDTO.setExpandLevel(expandLevel);
        expandBomTreeByFilterDTO.setIbaColumns(null);
        expandBomTreeByFilterDTO.setIsQueryIBA(true);
        expandBomTreeByFilterDTO.setIsNestedTree(isNestedTree);
        return this.typlmPartBomService.expandBomTreeByFilterNew(
                expandBomTreeByFilterDTO, isParent);
    }

    public RTExportFileDTO getDestFile(String destFileName) {
        if (org.apache.commons.lang3.StringUtils.isBlank(fileExportDefaultDir)) {
            throw RTErrorCodeEnum.NOT_FOUND_FILE_TEMPLATE.getException("临时目录未配置，请检查");
        }
        File file = new File(fileExportDefaultDir);
        if (!file.exists()) {
            FileUtil.mkdir(file);
        }
        if (!destFileName.contains(".")) {
            String fileName = destFileName + ".xlsx";
            String filePath = file.getAbsolutePath() + File.separator + fileName;
            log.info("===========提示信息============> 目标文件路径为：{}", filePath);
            return new RTExportFileDTO().setFileName(fileName).setFilePath(filePath);
        }
        String filePath = file.getAbsolutePath() + File.separator + destFileName;
        log.info("===========提示信息============> 目标文件路径为：{}", filePath);
        return new RTExportFileDTO().setFileName(destFileName).setFilePath(filePath);
    }

    public String getFilePath(String modelPath) {
        if (org.apache.commons.lang3.StringUtils.isBlank(modelPath)) {
            throw RTErrorCodeEnum.NOT_FOUND_FILE_TEMPLATE.getException("模板路径为空，请检查配置！");
        }
        String jarPath = PathUtil.getProjectPath();
        String path = jarPath + File.separator + modelPath;
        log.info("===========提示信息================> 模板文件路径为：{}", path);
        File file = new File(path);
        if (!file.exists()) {
            log.info("===========提示信息===================> 模板文件不存在");
            ClassPathResource resource = new ClassPathResource(File.separator + modelPath);
            if (!resource.exists()) {
                throw RTErrorCodeEnum.NOT_FOUND_FILE_TEMPLATE.getException("模板文件不存在，请检查配置");
            }
            try {
                return resource.getURI().getPath();
            } catch (IOException ioException) {
                throw RTErrorCodeEnum.NOT_FOUND_FILE_TEMPLATE.getException("获取模板文件异常，请检查配置");
            }
        }
        String absolutePath = file.getAbsolutePath();
        log.info("============提示信息==============> 模板路径为：{}", absolutePath);
        return absolutePath;
    }

    @Override
    public PartBomTreeByFilterVO queryChildPartsNoIba(String partNumber, String partOid, String view,
                                                      boolean isNestedTree, String lifecycleStateKey,
                                                      String expandLevel, boolean isParent) {
        List<ChildPartsFiltersDTO> conditions = new ArrayList<>();
        ChildPartsFiltersDTO childPartsFiltersDTO = new ChildPartsFiltersDTO();
        childPartsFiltersDTO.setExpandCondition("latest");
        if (StringUtils.isNotBlank(lifecycleStateKey)) {
            childPartsFiltersDTO.setLifecycleStateKey(lifecycleStateKey);
        }
        childPartsFiltersDTO.setView(view);
        conditions.add(childPartsFiltersDTO);
        ExpandBomTreeByFilterDTO expandBomTreeByFilterDTO = new ExpandBomTreeByFilterDTO();
        expandBomTreeByFilterDTO.setConditions(conditions);
        expandBomTreeByFilterDTO.setFatherOid(partOid);//设置oid
        expandBomTreeByFilterDTO.setFatherNumber(partNumber);
        expandBomTreeByFilterDTO.setFatherOtype(TableTypeConstrant.TY_PART_OTYPE);
        expandBomTreeByFilterDTO.setExpandLevel(expandLevel);
        expandBomTreeByFilterDTO.setIbaColumns(null);
        expandBomTreeByFilterDTO.setIsQueryIBA(false);
        expandBomTreeByFilterDTO.setIsNestedTree(isNestedTree);
        return this.typlmPartBomService.expandBomTreeByFilterNew(
                expandBomTreeByFilterDTO, isParent);
    }

    /**
     * POST请求通用方法
     *
     * @param urlString
     * @param body
     * @return
     */
    @Override
    public String sendPostRequest(String urlString, String username, String password, String body) {
        StringBuffer stringBuffer = new StringBuffer();
        try {
            // 1. 设置认证信息
            String auth = username + ":" + password;
            String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes());

            // 2. 创建连接
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Authorization", "Basic " + encodedAuth);
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setDoOutput(true);

            // 3. 发送请求体
            String jsonBody = body;
            try (OutputStream os = conn.getOutputStream()) {
                os.write(jsonBody.getBytes("UTF-8"));
            }

            // 4. 处理响应
            int responseCode = conn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                try (BufferedReader br = new BufferedReader(
                        new InputStreamReader(conn.getInputStream()))) {
                    String line;
                    while ((line = br.readLine()) != null) {
                        stringBuffer.append(line);
                    }
                }
            } else {
                log.info("请求失败，状态码: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return stringBuffer.toString();
    }


    @Override
    public String downloadFileToFtp(BigInteger fileId, String baseFilePath) {
        log.info("==========提示信息==========> 开始下载文件");
        log.info("==========提示信息==========> 文件ID为：{},baseFilePath:{}", fileId, baseFilePath);
        List<BigInteger> fileIds = new ArrayList<>();
        fileIds.add(fileId);
        fileIds.addAll(this.typlmContentReferenceLinkService.queryFileIlluStrationFileOids(fileIds));
        List<CadDownloadFileVO> cadDownloadFileVOList = this.typlmFileTransferService.getDownloadFileDTOS(fileIds,
                                                                                                          TyAccountContext.getUser()
                                                                                                                  .getOid());
        List<DownloadFileDTO> downloadFileDTOList = TyplmDownloadToolUtil.getDownloadFileDTOS(
                cadDownloadFileVOList);
        DownloadFileDTO downloadFileDTO = downloadFileDTOList.get(0);
        this.typlmEncryptService.recordFileNameKeys(new BigInteger(downloadFileDTO.getFileId()));
        DownLoadFileVO downLoadFileVO = this.typlmContentDataService.getInputStream(downloadFileDTO);
        return uploadFileToFTP(downLoadFileVO,baseFilePath);

    }

    public String uploadFileToFTP(DownLoadFileVO downLoadFileVO, String baseFilePath) {
        File file = downLoadFileVO.getFile();
        String fileName = downLoadFileVO.getFileName();
        UserDO userDO = typlmUserService.queryUserByName("admin");
        FTPClient ftpClient = new FTPClient();
        BufferedInputStream bis = null;
        String remoteFilePath = "";
        try {
            ftpClient.connect(server, port);
            int replyCode = ftpClient.getReplyCode(); // 获取 FTP 服务器的响应码
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                typlmLogger.errorInfo(userDO, LogEventEnum.UPLOAD, new Exception(replyCode + "：FTP文件上传失败"));
                log.warn("FTP 服务器连接失败，响应码：{}", replyCode);
                return "";
            }
            boolean login = ftpClient.login(username, password);
            log.info("ftp：IP地址：{}端口号：{}，用户名：{}，密码：{}", server, port, username, password);
            log.info("ftp登录：{}", login);
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            if (FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"))) {
                ftpClient.setControlEncoding("UTF-8");
            } else {
                // 如果服务器不支持UTF-8，则使用本地编码转换
                ftpClient.setControlEncoding("GBK");
            }

            bis = new BufferedInputStream(Files.newInputStream(file.toPath()));
            if (ftpClient.getControlEncoding().equals("UTF-8")) {
                remoteFilePath = baseFilePath + fileName;
            } else {
                // 如果服务器不支持UTF-8，则将中文转换为ISO-8859-1编码
                remoteFilePath = new String(baseFilePath.getBytes("GBK"), "ISO-8859-1") +
                        new String(fileName.getBytes("GBK"), "ISO-8859-1");
            }
            String remoteFolderPath = remoteFilePath.substring(0, Math.max(remoteFilePath.lastIndexOf("/"), 0));
            if (!createDirectories(ftpClient, remoteFolderPath)) {
                log.warn("无法创建远程目录：{}", remoteFolderPath);
                return "";
            }
            ftpClient.storeFile(remoteFilePath, bis);
            typlmLogger.info(userDO,LogEventEnum.UPLOAD,"文件上传FTP上传成功！");
        } catch (IOException e) {
            log.warn("文件上传失败！");
        } finally {
            try {
                if (bis != null) {
                    //字节输入流关闭时自动flush
                    bis.close();
                }
                ftpClient.logout();
                ftpClient.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return remoteFilePath;
    }

    private boolean createDirectories(FTPClient ftpClient, String remotePath) throws IOException {
        if (remotePath == null || remotePath.isEmpty()) {
            return false;
        }

        String[] pathElements = remotePath.split("/");
        StringBuilder currentPath = new StringBuilder();

        for (String dir : pathElements) {
            if (dir.isEmpty()) continue;

            currentPath.append("/").append(dir);
            // 检查当前编码
            String encodedDir = new String(dir.getBytes("GBK"), "ISO-8859-1");
            if (!ftpClient.changeWorkingDirectory(currentPath.toString())) {
                // 目录不存在，尝试创建

                if (!ftpClient.makeDirectory(encodedDir)) {
                    return false;
                }
                ftpClient.changeWorkingDirectory(currentPath.toString());
            }
        }
        return true;
    }


    @Override
    public Map<BigInteger, List<PartUsageCountVO>> queryPartUsageParent(List<BigInteger> partListOid, String logic,
                                                                        String level) {
        PartUsageCountQuery query = new PartUsageCountQuery();
        query.setPartIdList(partListOid);
        query.setQueryScope("latest");
        query.setQueryLogic(logic);
        query.setLevel(level);
        Map<BigInteger, List<PartUsageCountVO>> returnMap = typlmPartUsageService.queryPartUsageParent(query);
        buildUniqueKey(returnMap, query);
        return returnMap;
    }

    private void buildUniqueKey(Map<BigInteger, List<PartUsageCountVO>> returnMap, PartUsageCountQuery query) {
        if (!MapUtils.isEmpty(returnMap)) {
            Map<BigInteger, BigInteger> id2MasterMap = query.getMasterMap().values().stream().collect(Collectors.toMap(
                    PartDO::getOid, PartDO::getMasteredoid, (k1, k2) -> k1));
            returnMap.forEach((k, v) -> {
                Map<BigInteger, List<PartUsageCountVO>> parentMap = v.stream().collect(Collectors.groupingBy(PartUsageCountVO::getParentMasterOid));
                BigInteger initialParentId = id2MasterMap.get(k);
                List<PartUsageCountVO> partUsageCountVOS = parentMap.get(initialParentId);
                if (!CollectionUtils.isEmpty(partUsageCountVOS)) {
                    List<PartUsageCountVO> copyList = new ArrayList<>();
                    Iterator<PartUsageCountVO> var8 = partUsageCountVOS.iterator();

                    while (var8.hasNext()) {
                        PartUsageCountVO partUsageCountVO = var8.next();
                        this.recurseSetUniqueKey(partUsageCountVO, parentMap, initialParentId + "", copyList);
                    }

                    v.addAll(copyList);
                }
            });
        }
    }

    private void recurseSetUniqueKey(PartUsageCountVO currentPartUsageCountVO, Map<BigInteger, List<PartUsageCountVO>> parentMap, String prefixKey, List<PartUsageCountVO> copyList) {
        if (org.apache.commons.lang3.StringUtils.isEmpty(currentPartUsageCountVO.getUniqueKey())) {
            currentPartUsageCountVO.setParentUniqueKey(prefixKey);
            currentPartUsageCountVO.setUniqueKey(prefixKey + ":" + currentPartUsageCountVO.getMasterOid());
            List<PartUsageCountVO> partUsageCountVOS = parentMap.get(currentPartUsageCountVO.getMasterOid());
            if (CollectionUtils.isEmpty(partUsageCountVOS)) {
                return;
            }
            Iterator var6 = partUsageCountVOS.iterator();
            while (var6.hasNext()) {
                PartUsageCountVO partUsageCountVO = (PartUsageCountVO) var6.next();
                this.recurseSetUniqueKey(partUsageCountVO, parentMap, currentPartUsageCountVO.getUniqueKey(), copyList);
            }
        } else {
            PartUsageCountVO clonedPartUsageCountVO = (PartUsageCountVO) currentPartUsageCountVO.clone();
            clonedPartUsageCountVO.setParentUniqueKey(prefixKey);
            clonedPartUsageCountVO.setUniqueKey(prefixKey + ":" + currentPartUsageCountVO.getMasterOid());
            copyList.add(clonedPartUsageCountVO);
        }
    }

    @Override
    public Map<String, String> getIbaIdAndNameByType(String typeName) {
        Map<String, String> map = new HashMap<>();
        Set<BigInteger> set = new HashSet<>();

        List<String> typeNameList = Collections.singletonList(typeName);
        List<TypeTree> treeList = this.typlmTypeService.queryTypeTreeByInthid(typeNameList);
        getTypeOidByTypeName(treeList, set);

        if (set.isEmpty()) {
            return map;
        }

        for (BigInteger oid : set) {
            String oidStr = oid.toString();
            PdmPartFormData pdmPartFormData = this.typlmDynamicFormService.newQueryPartFormWithoutDetail(oidStr, null, null);
            List<PdmFormColumn> formData = pdmPartFormData.getPdmForm().getFormData();

            for (PdmFormColumn param : formData) {
                if (param.getOid() == null) {
                    continue;
                }
                map.put(param.getProp(), param.getIbaOid());
            }
        }

        return map;
    }

    private void getTypeOidByTypeName(List<TypeTree> treeList, Set<BigInteger> set) {
        for (TypeTree typeTree : treeList) {
            List<TypeTree> childList = typeTree.getChildList();
            set.add(typeTree.getOid());
            getTypeOidByTypeName(childList, set);
        }
    }

    @Override
    public String sendGetRequestToIPD(String url) throws IOException{
        OkHttpClient client = new OkHttpClient().newBuilder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .method("GET", null)
                .addHeader("Authorization", TyAccountContext.getToken())
                .build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    @Override
    public String sendPostRequestToIPD(String url, String data) throws IOException{
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, data);
        Request request = new Request.Builder()
                .url(url)
                .method("POST", body)
                .addHeader("Authorization", TyAccountContext.getToken())
                .addHeader("Content-Type", "application/json")
                .build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    @Override
    public String sendPutRequestToIPD(String url, String data) throws IOException{
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, data);
        Request request = new Request.Builder()
                .url(url)
                .method("PUT", body)
                .addHeader("Authorization", TyAccountContext.getToken())
                .addHeader("Content-Type", "application/json")
                .build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }
}


